package com.kehutong.common.interceptor;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.coraframework.inject.Inject;
import org.coraframework.inject.Singleton;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.HttpDespatcher;
import org.coraframework.mvc.http.HttpReqMsg;
import org.coraframework.mvc.http.interceptor.Exclude;
import org.coraframework.mvc.http.interceptor.Interceptor;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Entity;
import org.coraframework.upload.FileItem;
import org.coraframework.util.Objects;

import com.kehutong.common.DoveClient;
import com.kehutong.common.util.Token;



/**
 * 系统拦截器
 * @author ThinkGem
 * @version 2013-6-6
 */
@Singleton
@Exclude(WebService.class)
public class WwInterceptor extends Interceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(Logger.class);
	
	@Inject
	private DoveClient doveClient;
	
	@Override
	public Object intercept(HttpReqMsg req) throws Exception {
		try {
			Object rs = req.invoke();
			afterInvoker(req);
			return rs;
		} catch (Throwable th) {
			throw new Exception(th);
		}
	}
	
	
	private void afterInvoker(HttpReqMsg rq) {
		try {
			HttpDespatcher despatcher = (HttpDespatcher)rq.getDespatcher();
			if (despatcher.getInterceptorAnnotation().annotationType() != TrasIntercepter.class) {
				return;
			}
			
			TrasIntercepter intercep = (TrasIntercepter)despatcher.getInterceptorAnnotation();
			JSONObject jsonObject = getEntityParam(rq.getParams());
			
			HttpServletRequest req = rq.getHttpServletRequest();
			Token token = (Token)req.getAttribute("token");
			for (String url : intercep.value()) {
				doveClient.post(url, http->{
					Map<String, String> map = http.getHaders();
					if (!map.containsKey("companyNo")) {
						http.addHeader("companyNo", token.getCompanyNo());
					}
					http.setBody(jsonObject.toJSONString());
//					jsonObject.forEach((k, v)->http.addParam(k, v.toString()));
				});
			}
		} catch (Exception e) {
			logger.error("tras http error: ", e);
		}
	}
	/**
     * 获得用户远程地址
	 * @throws Exception 
     */
    
    private JSONObject getEntityParam(Object[] params) {
    	if (Objects.isEmpty(params)) {
    		return null;
    	}
    	
    	for (Object param : params) {
    		if (param instanceof Token) {
    			continue;
    		} 
    		
    		if (param instanceof FileItem) {
    			continue;
    		}
    		
    		if (param instanceof Entity) {
    			JSONObject json = ((Entity<?>)param).toJSON();
    			json.remove("deleted");
    			json.remove("updateTime");
    			json.remove("createTime");
    			return json;
    		}

			if (param instanceof Map) {
				JSONObject json = (JSONObject) param;
				json.remove("deleted");
				json.remove("updateTime");
				json.remove("createTime");
				return json;
			}
		}
    	
    	return null;
    }

}
